package com.zt.chatgpt.repository;

import com.zt.chatgpt.redis.IRedisService;
import com.zt.chatgpt.weixin.repository.IWeiXinRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author: zt
 * @Description: 微信仓储服务
 * @create: 2024-05-24 21:21
 */

@Slf4j
@Repository
public class WeiXinRepository implements IWeiXinRepository {

    private static final String KEY = "WEIXIN_CODE";

    @Resource
    private IRedisService redisService;
    @Override
    public String genCode(String openId) {
        // 1. 判断验证码是否存在
        String isExistCode = redisService.getValue(KEY + "_" + openId);
        if (StringUtils.isNotBlank(isExistCode)) {
            return isExistCode;
        }
        // 2. 上锁生成唯一验证码
        RLock lock = redisService.getLock(KEY);
        try {
            // 2.1 在15s内生成一个验证码
            lock.lock(15, TimeUnit.SECONDS);

            String code = RandomStringUtils.randomNumeric(4);
            // 防重效验：只要出现重复验证码就继续生成， 最多生成10次验证码
            for (int i = 0; i < 10 && StringUtils.isNotBlank(redisService.getValue(KEY + "_" + openId)); i++) {
                if (i < 3) {
                    return RandomStringUtils.randomNumeric(4);
                } else if (i < 5) {
                    return RandomStringUtils.randomNumeric(5);
                } else if (i < 9) {
                    return RandomStringUtils.randomNumeric(6);
                } else {
                    return "您的验证码获取失败，请重新回复101重新获取。";
                }
            }
            // 存储【3min】
            redisService.setValue(KEY + "_" + code, openId, 3 * 60* 1000);
            redisService.setValue(KEY + "_" + openId, code);

            return code;
        } finally {
            lock.unlock();
        }
    }
}
